<!DOCTYPE html>
<html lang="zh" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="fusion-docs">
<meta name="generator" content="Paradox, paradox-material-theme=0.6.0, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="fusion-docs">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>Interceptor Chain（拦截器链） · Akka Fusion</title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../assets/stylesheets/application-palette.22915126.css">
<meta name="theme-color" content="#3f51b5" />
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
data-md-color-primary="indigo"
data-md-color-accent="red"
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="Akka Fusion" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
Akka Fusion
</span>
<span class="md-header-nav__topic">
Interceptor Chain（拦截器链）
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/akka-fusion/akka-fusion"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
akka-fusion/akka-fusion
</div>
</a>

</div>
</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="Akka Fusion" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="Akka Fusion">
Akka Fusion
</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/akka-fusion/akka-fusion"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
akka-fusion/akka-fusion
</div>
</a>

</div>
<ul>
  <li><a href="../intro/index.html" class="page">简介</a></li>
  <li><a href="../core/index.html" class="page">核心</a>
  <ul>
    <li><a href="../core/akka-extension.html" class="page">Akka Extension（扩展）</a></li>
    <li><a href="../core/http-route.html" class="page">Http Route（异步处理器）</a></li>
    <li><a href="../core/fusion-core.html" class="page">FusionCore</a></li>
  </ul></li>
  <li><a href="../http/index.html" class="page">HTTP</a>
  <ul>
    <li><a href="../http/getting.html" class="page">开始</a></li>
    <li><a href="../http/management.html" class="page">管理API</a></li>
    <li><a href="../http/interceptor-chain.html" class="active page">Interceptor Chain（拦截器链）</a></li>
  </ul></li>
  <li><a href="../discovery-client/index.html" class="page">服务注册、发现（Client）</a>
  <ul>
    <li><a href="../discovery-client/nacos.html" class="page">连接 Nacos</a></li>
  </ul></li>
  <li><a href="../http-gateway/index.html" class="page">HTTP 代理网关</a></li>
  <li><a href="../jdbc/index.html" class="page">Jdbc</a></li>
  <li><a href="../slick/index.html" class="page">Slick</a></li>
  <li><a href="../mybatis/index.html" class="page">MyBatis</a>
  <ul>
    <li><a href="../mybatis/getting.html" class="page">起步</a></li>
    <li><a href="../mybatis/configuration.html" class="page">配置</a></li>
  </ul></li>
  <li><a href="../data-mongodb/index.html" class="page">Data Mongodb</a></li>
  <li><a href="../data-kafka/index.html" class="page">Data Kafka</a>
  <ul>
    <li><a href="../data-kafka/getting.html" class="page">开始</a></li>
    <li><a href="../data-kafka/producer.html" class="page">Kafka Producer</a></li>
    <li><a href="../data-kafka/consumer.html" class="page">Kafka Consumer</a></li>
  </ul></li>
  <li><a href="../inject/index.html" class="page">依赖管理</a>
  <ul>
    <li><a href="../inject/guice.html" class="page">使用 Guice 进行类依赖管理</a></li>
  </ul></li>
  <li><a href="../log/index.html" class="page">日志</a></li>
  <li><a href="../configuration/index.html" class="page">配置</a>
  <ul>
    <li><a href="../configuration/core.html" class="page">Fusion Core 配置</a></li>
    <li><a href="../configuration/http.html" class="page">Fusion HTTP 配置</a></li>
    <li><a href="../configuration/http-gateway.html" class="page">Fusion HTTP Gateway 配置</a></li>
    <li><a href="../configuration/jdbc.html" class="page">Fusion JDBC 配置</a></li>
    <li><a href="../configuration/slick.html" class="page">Fusion Slick 配置</a></li>
    <li><a href="../configuration/mybatis.html" class="page">Fusion Mybatis 配置</a></li>
    <li><a href="../configuration/mongodb.html" class="page">Fusion Mongodb 配置</a></li>
    <li><a href="../configuration/kafka.html" class="page">Fusion Kafka 配置</a></li>
  </ul></li>
  <li><a href="../reactivemanifesto.html" class="page">反应式宣言 2.0</a></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../http/interceptor-chain.html#interceptor-chain-拦截器链-" class="header">Interceptor Chain（拦截器链）</a>
  <ul>
    <li><a href="../http/interceptor-chain.html#应用拦截器链" class="header">应用拦截器链</a></li>
    <li><a href="../http/interceptor-chain.html#拦截器示例" class="header">拦截器示例</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 2.0.6
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../http/interceptor-chain.html#interceptor-chain-拦截器链-" class="header">Interceptor Chain（拦截器链）</a>
  <ul>
    <li><a href="../http/interceptor-chain.html#应用拦截器链" class="header">应用拦截器链</a></li>
    <li><a href="../http/interceptor-chain.html#拦截器示例" class="header">拦截器示例</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#interceptor-chain-拦截器链-" name="interceptor-chain-拦截器链-" class="anchor"><span class="anchor-link"></span></a>Interceptor Chain（拦截器链）</h1>
<p>Interceptor Chain在应用开发中是一个很常见的设计模式，Fusion提供了<code>HttpInterceptor</code>接口来支持拦截器链模式。</p>
<p>Scala是一门面向对象和函数式编程相融合的一门语言，在函数式编程中可通过函数的嵌套和各种高级处理来实现拦截器链的功能。</p>
<h2><a href="#应用拦截器链" name="应用拦截器链" class="anchor"><span class="anchor-link"></span></a>应用拦截器链</h2>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/akka-fusion/akka-fusion/tree/master/fusion-docs/src/main/scala/docs/core/HttpHandlerDoc.scala#L36-L50" target="_blank" title="Go to snippet source"></a><code class="language-scala">  trait HttpInterceptor {
    def filter(handler: HttpHandler): HttpHandler
  }

  def applyHttpInterceptorChain(httpHandler: HttpHandler, filters: Iterable[HttpInterceptor]): HttpHandler = {
    val duce: HttpHandler = filters.foldLeft(httpHandler) {
      (h, filter) =&gt;
//      interceptor.filter(handler)
//      val result = interceptor.filter(h)
//      req =&gt; result(req).getOrElse(h(req))
        req =&gt;
          filter.filter(h).apply(req)
    }
    duce
  }</code></pre>
<p>在<code>applyHttpInterceptorChain</code>函数中，对拦截器链<code>filters</code>应用<code>foldLeft</code>函数，即可非常优雅的应用每一个拦截器。</p>
<h2><a href="#拦截器示例" name="拦截器示例" class="anchor"><span class="anchor-link"></span></a>拦截器示例</h2>
<h3><a href="#拦截器示例-1-trace" name="拦截器示例-1-trace" class="anchor"><span class="anchor-link"></span></a>拦截器示例 1：trace</h3>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/akka-fusion/akka-fusion/tree/master/fusion-docs/src/main/scala/docs/core/HttpHandlerDoc.scala#L100-L118" target="_blank" title="Go to snippet source"></a><code class="language-scala">class TraceHttpInterceptor(system: classic.ActorSystem) extends HttpInterceptor {
  import system.dispatcher

  override def interceptor(route: Route): Route = { ctx =&gt;
    val req = ctx.request
    val traceHeader = RawHeader(&quot;trace-id&quot;, ObjectId.get().toHexString)
    val headers = traceHeader +: req.headers
    val request = req.copy(headers = headers)
    route(ctx.withRequest(request)).map {
      case RouteResult.Complete(response) =&gt; RouteResult.Complete(toTrace(response, traceHeader))
      case a @ RouteResult.Rejected(_)    =&gt; a
    }
  }

  private def toTrace(response: HttpResponse, traceHeader: RawHeader): HttpResponse = {
    val headers = traceHeader +: response.headers
    response.copy(headers = headers)
  }
}</code></pre>
<p><code>TraceHttpInterceptor</code>实现了给接收到的HTTP请求添加 <strong>trace id</strong> 的功能，这在微服务中监控调用链非常有用。</p>
<h3><a href="#拦截器示例-2-不做任务处理" name="拦截器示例-2-不做任务处理" class="anchor"><span class="anchor-link"></span></a>拦截器示例 2：不做任务处理</h3>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/akka-fusion/akka-fusion/tree/master/fusion-docs/src/main/scala/docs/core/HttpHandlerDoc.scala#L92-L96" target="_blank" title="Go to snippet source"></a><code class="language-scala">class NothingHttpInterceptor extends HttpInterceptor {
  override def interceptor(route: Route): Route = { ctx =&gt;
    route(ctx)
  }
}</code></pre>
<p>直接返回<code>handler</code>，并不对HTTP请求过程做任务处理，就像 <code>NothingHttpIntercepter</code> 那样。你可以加入判断逻辑，</p>
<h3><a href="#拦截器示例-3-终止调用链" name="拦截器示例-3-终止调用链" class="anchor"><span class="anchor-link"></span></a>拦截器示例 3：终止调用链</h3>
<p>某个拦截器想终止调用链的执行，在转换函数中抛出一个异常即可：</p>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/akka-fusion/akka-fusion/tree/master/fusion-docs/src/main/scala/docs/core/HttpHandlerDoc.scala#L81-L87" target="_blank" title="Go to snippet source"></a><code class="language-scala">  class TerminationHttpInterceptor extends HttpInterceptor {
    override def filter(handler: HttpHandler): HttpHandler = { req =&gt;
      //handler(req).flatMap(resp =&gt; Future.failed(HttpResponseException(resp)))
//      handler(req).map(resp =&gt; throw HttpResponseException(resp))
      throw HttpResponseException(HttpResponse(StatusCodes.InternalServerError))
    }
  }</code></pre>
</div>
<div>
<a href="https://github.com/akka-fusion/akka-fusion/tree/master/fusion-docs/src/main/paradox/http/interceptor-chain.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
2.0.6
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../http/management.html" title="管理API" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
管理API
</span>
</div>
</a>
<a href="../discovery-client/index.html" title="服务注册、发现（Client）" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
服务注册、发现（Client）
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
<div class="md-footer-social">
<a href="https://akka-fusion.github.io/akka-fusion/" class="md-footer-social__link fa fa-globe"></a><a href="https://github.com/akka-fusion" class="md-footer-social__link fa fa-github"></a><a href="https://weibo.com/yangbajing" class="md-footer-social__link fa fa-globe"></a>
</div>

</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
